<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="记录编码" prop="finaCode">
        <el-input v-model="queryParams.finaCode" placeholder="请输入记录编码" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="日期" prop="finaDate">
        <el-date-picker clearable v-model="queryParams.finaDate" type="date" value-format="yyyy-MM-dd" placeholder="日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="一级科目" prop="subId1">
        <!-- <el-input v-model="queryParams.subName1" placeholder="请输入一级科目" clearable @keyup.enter.native="handleQuery" /> -->
      <el-select v-model="queryParams.subId1" placeholder="请选择一级科目"  clearable @keyup.enter.native="handleQuery"  @change="getSubListBySubIdSearch(2,queryParams.subId1)">
        <el-option
            v-for="item in sub1Options"
            :key="item.subId"
            :label="item.subName"
            :value="item.subId"
            :disabled="item.delFlag == 'N'"
          ></el-option>
      </el-select>
      </el-form-item>
      <el-form-item label="二级科目" prop="subId2">
        <!-- <el-input v-model="queryParams.subName2" placeholder="请输入二级科目" clearable @keyup.enter.native="handleQuery" /> -->
        <el-select v-model="queryParams.subId2" placeholder="请选择二级科目"  clearable @keyup.enter.native="handleQuery" @change="getSubListBySubIdSearch(3,queryParams.subId2)">
          <el-option
              v-for="item in sub2Options"
              :key="item.subId"
              :label="item.subName"
              :value="item.subId"
              :disabled="item.delFlag == 'N'"
            ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="三级科目" prop="subId3">
        <el-select v-model="queryParams.subId3" placeholder="请选择三级科目"  clearable @keyup.enter.native="handleQuery" @change="getSubListBySubIdSearch(4,queryParams.subId3)">
          <el-option
              v-for="item in sub3Options"
              :key="item.subId"
              :label="item.subName"
              :value="item.subId"
              :disabled="item.delFlag == 'N'"
            ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="四级科目" prop="subId4">
        <el-select v-model="queryParams.subId4" placeholder="请选择四级科目"  clearable @keyup.enter.native="handleQuery" @change="getSubListBySubIdSearch(5,queryParams.subId4)">
          <el-option
              v-for="item in sub4Options"
              :key="item.subId"
              :label="item.subName"
              :value="item.subId"
              :disabled="item.delFlag == 'N'"
            ></el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="用途" prop="finaAbstract">
        <el-select v-model="queryParams.finaAbstract"
        placeholder="请选择用途"  clearable @keyup.enter.native="handleQuery">
          <el-option
              v-for="item in finaAbstractOptions"
              :key="item.subId"
              :label="item.subName"
              :value="item.subId"
              :disabled="item.delFlag == 'N'"
            ></el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="客户名称" prop="cusName">
        <el-input v-model="queryParams.cusName" placeholder="请输入客户名称" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="经办人" prop="finaOperatorId">
        <el-select v-model="queryParams.finaOperatorId"  placeholder="请输入经办人" clearable
          @keyup.enter.native="handleQuery">
          <el-option
            v-for="dict in dict.type.cash_opter"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          ></el-option>
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['mes:fina:cash:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
          v-hasPermi="['mes:fina:cash:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['mes:fina:cash:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['mes:fina:cash:export']">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="cashList" @selection-change="handleSelectionChange"
    :cell-style="cellStyle">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="记录编码" align="center" prop="finaCode" />
      <el-table-column label="日期" align="center" prop="finaDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.finaDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="一级科目" align="center" prop="subName1" />
      <el-table-column label="二级科目" align="center" prop="subName2" />
      <el-table-column label="三级科目" align="center" prop="subName3" />
      <el-table-column label="四级科目" align="center" prop="subName4" />
      <el-table-column label="用途" align="center" prop="finaAbstract" />
      <el-table-column label="客户名称" align="center" prop="cusName" />
      <el-table-column label="经办人" align="center" prop="finaOperatorName" />
      <el-table-column label="收入" align="center" prop="finaIn" />
      <el-table-column label="支出" align="center" prop="finaOut" />
      <el-table-column label="摘要" align="center" prop="remark" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['mes:fina:cash:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['mes:fina:cash:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改日记账记录对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="8">
            <el-form-item label="记录编码" prop="finaCode">
              <el-input v-model="form.finaCode" readonly="readonly" maxlength="64" v-if="optType == 'view'"/>
              <el-input v-model="form.finaCode" placeholder="请输入记录编码" maxlength="64" v-else/>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item  label-width="80">
              <el-switch v-model="autoGenFlag"
                  active-color="#13ce66"
                  active-text="自动生成"
                  @change="handleAutoGenChange(autoGenFlag)" v-if="optType != 'view'">
              </el-switch>
            </el-form-item>
          </el-col>


          <el-col :span="12">
            <el-form-item label="日期" prop="finaDate">
              <el-date-picker clearable v-model="form.finaDate" type="date" value-format="yyyy-MM-dd" placeholder="请选择日期">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="一级科目" prop="subId1">
              <el-select v-model="form.subId1" @change="getSubListBySubId(2,form.subId1)">
                <el-option
                    v-for="item in sub1Options"
                    :key="item.subId"
                    :label="item.subName"
                    :value="item.subId"
                    :disabled="item.delFlag == 'N'"
                  ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="二级科目" prop="subId2"  >
              <el-select v-model="form.subId2" @change="getSubListBySubId(3,form.subId2)">
                <el-option
                    v-for="item in sub2Options"
                    :key="item.subId"
                    :label="item.subName"
                    :value="item.subId"
                    :disabled="item.delFlag == 'N'"
                  ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="三级科目" prop="subId3">
              <el-select v-model="form.subId3"  @change="getSubListBySubId(4,form.subId3)">
                <el-option
                    v-for="item in sub3Options"
                    :key="item.subId"
                    :label="item.subName"
                    :value="item.subId"
                    :disabled="item.delFlag == 'N'"
                  ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="四级科目" prop="subId4">
              <el-select v-model="form.subId4" @change="getSubListBySubId(5,form.subId4)">
                <el-option
                    v-for="item in sub4Options"
                    :key="item.subId"
                    :label="item.subName"
                    :value="item.subId"
                    :disabled="item.delFlag == 'N'"
                  ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="用途" prop="finaAbstract"  v-show="finaAbstractShow">
              <el-select v-model="form.finaAbstract"
               @change="getSubListBySubId(6,form.finaAbstract)">
                <el-option
                    v-for="item in finaAbstractOptions"
                    :key="item.subId"
                    :label="item.subName"
                    :value="item.subId"
                    :disabled="item.delFlag == 'N'"
                  ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label-form-item label="客户名称" prop="cusName"  v-show="cusNameShow">
              <el-input v-model="form.cusName" type="textarea" placeholder="请输入客户名称"
              />
            </el-form-item>
          </el-col>

        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="经办人" prop="finaOperatorId">
              <el-select v-model="form.finaOperatorId" placeholder="请输入经办人"  :disabled="opteratorIsHY">
                <el-option
                  v-for="dict in dict.type.cash_opter"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label-form-item label="摘要" prop="remark">
              <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="收入" prop="finaIn" v-show="inShow">
              <el-input v-model="form.finaIn" placeholder="请输入收入(录入数字)"
               οnkeyup="value=value.replace()"  maxlength="4" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="支出" prop="finaOut" v-show="outShow">
              <el-input v-model="form.finaOut" placeholder="请输入支出"/>
            </el-form-item>
          </el-col>
        </el-row>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import { listCash, getCash, delCash, addCash, updateCash } from "@/api/fina/cash";
  import { listSub,listByOrder } from "@/api/fina/sub";
  import {genCode} from "@/api/system/autocode/rule"

  export default {
    name: "Cash",
    dicts: ['cash_opter'],
    data() {
      return {
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // 出纳管理列表格数据
        cashList: [],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        // 收入显示
        inShow:true,
        // 支出显示
        outShow:true,
        // 用途显示
        finaAbstractShow:false,
        // 客户名称显示
        cusNameShow:false,
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          finaCode: null,
          finaDate: null,
          subId1: null,
          subName1:null,
          subId2: null,
          subName2:null,
          subId3: null,
          subName3:null,
          subId4: null,
          subName4:null,
          orderNum: null,
          finaAbstract: null,
          finaOperatorId: null,
          finaOperatorName: null,
          finaIn: null,
          finaOut: null,
          finaBalance: null,
          status: null,
        },
        // 表单参数
        form: {},
        //弹框的操作类型 view add edit
        optType: undefined,
        //自动生成物料编码标识
        autoGenFlag: false,
        //是否海洋科技
        opteratorIsHY:false,
        //所有科目列表
        subAllOptions:[],
        //科目一列表
        sub1Options: [],
        //科目二列表
        sub2Options: [],
        //科目三列表
        sub3Options: [],
        //科目四列表
        sub4Options: [],
        //科目四列表
        finaAbstractOptions: [],
        //科目一选中id
        sub1IdSel:0,
        //科目2选中id
        sub2IdSel:0,
        //科目3选中id
        sub3IdSel:0,
        //科目4选中id
        sub4IdSel:0,
        // 表单校验
        rules: {
          finaCode: [
            { required: true, message: "记录编码不能为空", trigger: "blur" },
            { max: 64, message: '记录编码长度必须小于64个字符', trigger: 'blur' }
          ],
          finaDate: [
            { required: true, message: "日期不能为空", trigger: "blur" }
          ],
          subId1: [
            { required: true, message: "一级科目不能为空",trigger: "blur"}
          ],
          subId2: [
            { required: true, message: "二级科目不能为空", trigger: "blur" },
          ],
          subId3: [
            { required: true, message: "三级科目不能为空",trigger: "blur"}
          ],
          subId4: [
            { required: true, message: "四级科目不能为空", trigger: "blur" },
          ],
          finaAbstract: [
            { required: true, message: "用途不能为空",trigger: "blur"}
          ],
          finaOperatorId: [
            { required: true, message: "经办人不能为空", trigger: "blur" },
          ],
          finaIn: [
            { required: false, validator:this.isInMoney.bind(this) ,message: "请录入收入金额(精确小数点2为)", trigger: "blur" },
          ],
          finaOut: [
            { required: false, validator:this.isOutMoney.bind(this) ,message: "请录入支出金额(精确小数点2为)", trigger: "blur" },
          ],
          cusName: [
            { required: false, message: "客户名称不能为空", trigger: "blur" },
          ],

        }
      };
    },
    created() {
      this.getList();
      this.getSubList();
    },
    methods: {
      /** 查询出纳管理列列表 */
      getList() {
        this.loading = true;
        listCash(this.queryParams).then(response => {
          this.cashList = response.rows;
          this.total = response.total;
          this.loading = false;
        });
      },
      /** 获取科目下拉列表 */
      getSubList(){
        listSub(null).then(response => {
          // debugger;
          var data = response.rows
          this.subAllOptions = data
          // console.log("data::::",data)
          for(let i=0;i<data.length;i++){
            var item = data[i]
            // console.log("item::::",item)
            var orderNum = item.orderNum
            if(orderNum == 1){
              this.sub1Options.push(item)
            }
            else if(orderNum == 2){
              this.sub2Options.push(item)
            }else if(orderNum == 3){
              this.sub3Options.push(item)
            }else if(orderNum == 4){
              this.sub4Options.push(item)
            }
          }
        });

      },
      /** 根据上一级获取对应下一级列表 */
      getSubListBySubId(row,subId){
        var data = this.subAllOptions
        var subOptions = []
        for(let i=0;i<data.length;i++){
          var item = data[i]
          // console.log("item::::",item)
          var orderNum = item.orderNum
          if(row == 2){
            if(item.subId == subId){
              this.form.subName1 = item.subName
            }
          }else if(row == 3){
            if(item.subId == subId){
              this.form.subName2 = item.subName
            }
          }else if(row == 4){
            if(item.subId == subId){
              this.form.subName3 = item.subName
              if(item.subName == "海洋科技"){
                this.form.finaOperatorId = 1001
                this.form.finaOperatorName = "海洋科技"
                // this.form.finaOperatorName = {"key":1001,"label":"海洋科技","value":1001}
                this.opteratorIsHY = true
                this.rules.finaOperatorId[0].required = false
              }else{
                this.opteratorIsHY = false
                this.form.finaOperatorName = ""
                this.rules.finaOperatorId[0].required = true
              }
            }

          }else if(row == 5){
              if(item.subId == subId){
                this.form.subName4 = item.subName
              }
          }
          if(item.parentId == subId){
            subOptions.push(item)
          }

        }

        if(row == 2){

          if(subId == 101){//应收
            this.inShow = true
            this.outShow = false
            this.rules.finaIn[0].required = true
            this.rules.finaOut[0].required = false
          }else if(subId == 102){// 应付
            this.inShow = false
            this.outShow = true
            this.rules.finaIn[0].required = false
            this.rules.finaOut[0].required = true
          }

          this.form.subId2 = null
          this.sub2Options = subOptions
        }else if(row == 3){
          this.form.subId3 = null
          this.sub3Options = subOptions
        }else if(row == 4){
          this.form.subId4 = null
          this.sub4Options = subOptions
        }else if(row == 5){
          this.form.finaAbstract = null
          this.finaAbstractOptions = subOptions
          // console.log("this.finaAbstractShow",this.finaAbstractShow)
          if(subOptions != null && subOptions.length > 0){//存在用途
          // console.log("subOptions",subOptions,"存在用途")
            this.finaAbstractShow = true
            this.rules.finaAbstract[0].required = true
          }else{// 不需要录入用途
          // console.log("subOptions",subOptions,"不需要录入用途")
            this.finaAbstractShow = false
            this.rules.finaAbstract[0].required = false
          }
          //判断是否存在需要录入客户名称

          if(this.form.subName4 != undefined && this.form.subName4 != null && this.form.subName4 != ""){
            var subNameTemp = this.form.subName4;
            console.log("subNameTemp",subNameTemp)
            console.log("this.cusNameShow",this.cusNameShow)
            if(subNameTemp.indexOf("客户") != -1){
            console.log("subNameTemp",subNameTemp,"需要录入客户")
              this.cusNameShow = true
              this.rules.cusName[0].required = true
            }else{
            console.log("subNameTemp",subNameTemp,"不需要录入客户")
              this.cusNameShow = false
              this.rules.cusName[0].required = false
            }
          }

        }

      },

      /** 搜索根据上一级获取对应下一级列表 */
      getSubListBySubIdSearch(row,subId){
        var data = this.subAllOptions
        var subOptions = []
        for(let i=0;i<data.length;i++){
          var item = data[i]
          var orderNum = item.orderNum
          if(item.parentId == subId){
            subOptions.push(item)
          }
        }

        if(row == 2){

          this.queryParams.subId2 = null
          this.sub2Options = subOptions
        }else if(row == 3){
          this.queryParams.subId3 = null
          this.sub3Options = subOptions
        }else if(row == 4){
          this.queryParams.subId4 = null
          this.sub4Options = subOptions
        }else if(row == 5){
          this.queryParams.finaAbstract = null
          this.finaAbstractOptions = subOptions
        }

      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },
      // 表单重置
      reset() {
        this.form = {
          finaId: null,
          finaCode: null,
          finaDate: null,
          subId1: null,
          subName1:null,
          subId2: null,
          subName2:null,
          subId3: null,
          subName3:null,
          subId4: null,
          subName4:null,
          orderNum: null,
          finaAbstract: null,
          finaOperatorId: null,
          finaIn: null,
          finaOut: null,
          finaBalance: null,
          remark: null,
          status: "0",
          delFlag: null,
          createBy: null,
          createTime: null,
          updateBy: null,
          updateTime: null
        };
        this.autoGenFlag = false;
        this.resetForm("form");
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm("queryForm");
        this.handleQuery();
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.finaId)
        this.single = selection.length !== 1
        this.multiple = !selection.length
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.reset();
        this.open = true;
        this.title = "添加日记账记录";
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.reset();
        const finaId = row.finaId || this.ids
        getCash(finaId).then(response => {
          this.form = response.data;
          this.open = true;
          this.title = "修改日记账记录";
        });
      },
      /** 提交按钮 */
      submitForm() {
        this.$refs["form"].validate(valid => {
          if (valid) {
            if (this.form.finaId != null) {
              updateCash(this.form).then(response => {
                this.$modal.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              });
            } else {
              addCash(this.form).then(response => {
                this.$modal.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              });
            }
          }
        });
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const finaIds = row.finaId || this.ids;
        this.$modal.confirm('是否确认删除日记账记录编号为"' + finaIds + '"的数据项？').then(function() {
          return delCash(finaIds);
        }).then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        }).catch(() => {});
      },
      /** 导出按钮操作 */
      handleExport() {
        this.download('fina/cash/export', {
          ...this.queryParams
        }, `cash_${new Date().getTime()}.xlsx`)
      },
      //自动生成物料编码
      handleAutoGenChange(autoGenFlag){
        // debugger;
        if(autoGenFlag){
          genCode('FINA_CODE').then(response =>{
            console.log("response>>>>>>",response)
            this.form.finaCode = response;
          });
         }else{
            this.form.finaCode = null;
         }
      },
      cellStyle({ row, column, rowIndex, columnIndex }) {
        if (column.property === 'subName3' || column.property === 'subName4') {
          if (row.subName3 === '海洋科技' || row.subName4 === '海洋科技') {
            return 'color: red;';
          }
        }
      },
      // 收入金额验证表达式
      isInMoney(rule,value,callback){
        const { required } = rule
          if (value === '') {
            if (required) callback('请输入收入金额')
            else callback()
          } else if (!/^\d+(\.\d{0,2})?$/.test(value)) {
            callback('请输入正确的数值（最多只能保留两位小数）')
          } else if (value > 10000000) {
            callback('单次输入不得大于10000000')
          } else {
            callback()
          }
      },
      // 支出金额验证表达式
      isOutMoney(rule,value,callback){
        const { required } = rule
          if (value === '') {
            if (required) callback('请输入支出金额')
            else callback()
          } else if (!/^\d+(\.\d{0,2})?$/.test(value)) {
            callback('请输入正确的数值（最多只能保留两位小数）')
          } else if (value > 10000000) {
            callback('单次输入不得大于10000000')
          } else {
            value = 0-value
            callback()
          }
      }
    }
  };
</script>
